package fyp.spedmew.connector;

import android.os.AsyncTask;
import android.util.Log;

import com.google.api.client.http.HttpStatusCodes;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.InputStream;

import fyp.spedmew.util.Constant;


public class UploadImageATask extends AsyncTask<Object, Void, Boolean> {
    private static final String TAG = new Object(){}.getClass().getCanonicalName();
    private static final String PRE_UPLOAD_URL = "http://" + Constant.APP_ADDRESS + ":" + Constant.APP_PORT + "/getUpload";

    @Override
    protected Boolean doInBackground(Object... params) {
        File file = (File) params[0];
        Long jobId = (Long) params[1];
        HttpClient client = new DefaultHttpClient();
        HttpPost post;
        try {
            // setup
            post = new HttpPost(getUploadURL());
            FileBody fileBody = new FileBody(file);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addPart("myFile", fileBody);
            builder.addTextBody("jobId", jobId.toString());
            post.setEntity(builder.build());
            // run
            HttpResponse response = client.execute(post); //Here "uploaded" servlet is automatically invoked
            // process response
            if(response.getStatusLine().getStatusCode() == HttpStatusCodes.STATUS_CODE_OK) {
                return Boolean.TRUE;
            } else {
                return Boolean.FALSE;
            }

        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
            return Boolean.FALSE;
        }
    }

    public String getUploadURL() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(PRE_UPLOAD_URL);
        HttpResponse response = client.execute(request);

        HttpEntity urlEntity = response.getEntity();
        InputStream in = urlEntity.getContent();
        String str = "";
        while (true) {
            int ch = in.read();
            if (ch == -1)
                break;
            str += (char) ch;
        }

        return str;
    }
}
